//
// Created by mio on 25-5-12.
//

#include "AudioCapture.h"
#include "WASAPICapture.h"
#include "AudioBuffer.h"

AudioCapture::AudioCapture() : capture_(nullptr), audio_buffer_(nullptr)
{
    capture_.reset(new WASAPICapture());
}

AudioCapture::~AudioCapture()
{

}

bool AudioCapture::Init(uint32_t size)
{
    if (isInitialized_) { return true; }

    if (capture_->Init() < 0) { return false; }
    else
    {
        WAVEFORMATEX* audioFmt = capture_->GetAudioFormat();
        channels_ = audioFmt->nChannels;
        sampleRate_ = audioFmt->nSamplesPerSec;
        bits_per_samples_ = audioFmt->wBitsPerSample;
    }

    // 创建Buffer
    audio_buffer_.reset(new AudioBuffer(size));

    // 启动捕获
    if (StartCapture() < 0) { return false; }
    isInitialized_ = true;
    return true;
}

void AudioCapture::Close()
{
    if (isInitialized_)
    {
        StopCapture();
        isInitialized_ = false;
    }
}

int AudioCapture::GetSamples()
{
    // 从缓冲区获取当前有多少音频数据
    return audio_buffer_->size() * 8 / bits_per_samples_ / channels_;
}

int AudioCapture::Read(uint8_t *data, uint32_t samples)
{
    if (samples > this->GetSamples()) { return 0; }
    audio_buffer_->read((char*)data, samples * bits_per_samples_ / 8 * channels_);
    return samples;
}

int AudioCapture::StartCapture()
{
    capture_->SetCallback([this](const WAVEFORMATEX *mixFormat, uint8_t *data, uint32_t samples) {
        channels_ = mixFormat->nChannels;
        sampleRate_ = mixFormat->nSamplesPerSec;
        bits_per_samples_ = mixFormat->wBitsPerSample;
        // 将数据写入缓冲区
        audio_buffer_->write((char*)data, mixFormat->nBlockAlign * samples);
    });

    audio_buffer_->clear();
    if (capture_->Start() < 0) { return -1; }
    isStarted_ = true;
    return 0;
}

int AudioCapture::StopCapture()
{
    capture_->Stop();
    isStarted_ = false;
    return 0;
}
